package com.yckj.web.uol.servlet;


import com.yckj.web.uol.entity.User;
import com.yckj.web.uol.service.Impl.UserServiceImpl;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Classname Loginservlet
 * @Description TODO
 * @Copyright:Copyright(c) 2021
 * @Company 英才汇硕信息科技有限公司
 * @Author xu
 * @Version 1.0
 * @Date 2021/7/21 11:39
 */
@WebServlet("/login")
public class Loginservlet extends HttpServlet {
    private Logger logger = Logger.getLogger(this.getClass());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        logger.debug(username);
        logger.debug(password);
        User user = new User();
        user.setUsername(username);
        user.setPasswords(password);
        //获取用户输入的验证码
        String code = req.getParameter("code");
        System.out.println("code"+code);

        //获取session中验证码
        String code1 = (String) req.getSession().getAttribute("code");
        //判断验证码是否正确
        System.out.println("code1"+code1);
        if(!code.equals(code1)){
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
            req.setAttribute("code","验证码错误");
            return;
        }
        //调用业务层的方法登录
        UserServiceImpl userService = new UserServiceImpl();
        User user1 = userService.login(user);
        PrintWriter writer = resp.getWriter();
        if (user1!=null){
            logger.debug("登录成功");
            //发送到首页
            resp.sendRedirect(req.getContextPath()+"/index.jsp");
        }else {
            logger.debug("登录失败");
            //发送到登录页面
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
        }
    }
}
